package com.yunb.service;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

import com.alibaba.fastjson.JSONObject;
import com.yunb.entity.Basic;
import com.yunb.util.JedisUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class GenRedPack {

	@Resource
	private  JedisUtils jedis;

	/**
	 * 多线程模拟红包池初始化  Jedis类
	 */
	public void genHongBao() throws InterruptedException {

		//发枪器
		final CountDownLatch latch = new CountDownLatch(Basic.threadCount);
		
		for(int i = 0 ; i < Basic.threadCount; i++){
			final int page = i;
			Thread thread = new Thread(){
				@Override
				public void run(){
					latch.countDown();
					try {
						latch.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					//每个线程要初始化多少个红包
					int per = Basic.honBaoCount/Basic.threadCount;
					
					JSONObject object = new JSONObject();

					for(int j = page * per ; j < (page+1) * per; j++){
						object.put("id", "rid_"+j); //红包ID
						System.out.println("money=>"+j);
						object.put("money", j);   //红包金额
						jedis.lpush("hongBaoPoolKey", object.toJSONString());
					}
				}
			};
			thread.start();
		}
	}

	public void initRedBao() throws InterruptedException {
		jedis.del("hongBaoPoolKey","userIdRecordKey","hongBaoDetailListKey");

		JSONObject object = new JSONObject();
		Random random = new Random();
		int averageAmount = Basic.moneyTotal / Basic.honBaoCount;
		for(int i = 1; i <= Basic.honBaoCount; i++) {
			int offset = random.nextInt(100) - 50; // 生成-50到50之间的随机偏移量
			int randomAmount = averageAmount + offset;
			object.put("id", "rid_" + i); //红包ID
			// 通过总金额的随机数，分配红包金额
			object.put("money", randomAmount);   //红包金额
			jedis.lpush("hongBaoPoolKey", object.toJSONString());
		}
	}
}
